import {
	defineStore
} from 'pinia'
import http from '@/common/request.js'
import {
	navTo,
	setLoadingToast
} from '@/common/utils'
import {
	getDriveDetails,
	getInfo,
	login
} from '@/api/drive'

const keyNames = 'LOGISTICE_DRIVER'

const useLogisicsDriver = defineStore(keyNames, {
	state: () => {
		return {
			// 司机登录成功后的信息
			userInfo: {},
			// 存放token
			token: null,
		}
	},

	getters: {
		getUserinfo: state => state.userInfo,
		getToken: state => state.token
	},

	actions: {
		// 存储userInfo 信息
		setUserinfo(payload) {
			this.userInfo = payload
		},
		setToken(token) {
			this.token = token
		},
		clear() {
			this.userInfo = {}
			this.token = ''
		},
		// 存储userInfo 信息
		setUserinfo(payload) {
			const {
				token,
				...args
			} = payload
			this.userInfo = args
			// 如果登录成功信息中有token
			if (token) {
				this.token = token
			}
		},
		// 司机登录
		companyLogin(params) {
			const that = this
			try {
				setLoadingToast('正在登陆...')
				login(params).then(res => {
					// console.log("res ============> ", res.data);
					that.setToken(res.data)
					that.getInfo()
				})
				// 前往司机首页
				// navTo("/pages/driver/index/index")
			} catch (e) {
				//TODO handle the exception
			}
		},
		// 获取司机信息
		getInfo() {
			const that = this
			try {
				getInfo().then(res => {
					console.log("res ========> ", res);
					that.getDetails(res.data.uId)
				})
			} catch (e) {
				//TODO handle the exception
				uni.hideLoading()
			}
		},
		// 获取报车人详情
		getDetails(id) {
			let that = this
			try {
				getDriveDetails(id).then(res => {
					setTimeout(() => {
						that.setUserinfo(res.data)
						uni.hideLoading()
						// 前往公司首页
						navTo("/pages/driver/index/index")
					}, 200)
				})
			} catch (e) {
				//TODO handle the exception
				uni.hideLoading()
			}
		},

	},
	// 数据持久化
	unistorage: true // 开启后对 state 的数据读写都将持久化
})

export default useLogisicsDriver